<template>
  <div class="app-container">

    <!-- 搜索表单 -->
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item>
        <el-input v-model="queryParams.number" placeholder="请输入员工编号" />
      </el-form-item>

      <el-form-item style="margin-left: 23px;">
        <el-input v-model="queryParams.name" placeholder="请输入员工姓名" />
      </el-form-item>

      <el-form-item style="margin-left: 23px;">
        <el-input v-model="queryParams.phoneNumber" placeholder="请输入员工电话" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="onSubmit">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="clear">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="dialogVisible = true">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
        >导出</el-button>
      </el-col>
    </el-row>

    <!--添加数据对话框表单-->
    <el-dialog ref="form" title="编辑信息" :visible.sync="dialogVisible" width="30%">
      <el-form ref="teacher" :model="teacher" :rules="rules" label-width="80px" size="mini">
        <el-form-item label="员工编号" prop="number">
          <el-input v-model="teacher.number" />
        </el-form-item>

        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="teacher.name" />
        </el-form-item>

        <el-form-item label="联系电话" prop="phoneNumber">
          <el-input v-model="teacher.phoneNumber" />
        </el-form-item>

        <el-form-item label="员工邮箱" prop="email">
          <el-input v-model="teacher.email" />
        </el-form-item>
        <el-form-item style="margin-left: 50px;">
          <el-button type="primary" @click="add('teacher')">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 表格 -->
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="number" label="员工编号" width="150px" align="center" />
      <el-table-column prop="name" label="姓名" width="150px" align="center" />
      <el-table-column prop="phoneNumber" label="联系电话" width="280px" align="center" />
      <el-table-column prop="email" label="邮箱" width="280px" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="update(scope.row.id)"
          >修改</el-button>
          <el-button
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="deleteById(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页工具条-->
    <el-pagination
      :background="background"
      :current-page="current"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      style="margin-top: 8px;"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { add, page, update, selectById, deleteById } from '@/api/teacher.js'
import { parseTime } from '@/utils'

export default {
  data() {
    return {
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      current: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      queryParams: {
        number: '',
        name: '',
        phoneNumber: ''
      },
      teacher: {
        id: '',
        number: '',
        name: '',
        phoneNumber: '',
        email: ''
      },
      rules: {
        number: [
          { required: true, message: '请输入员工编号', trigger: 'change' },
          { pattern: /^\d{3}$/, message: '员工编号必须为3位数字', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '电话号码必须为11位数字,且以1开头,第二位是3-9之间的数字', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      },
      tableData: [],
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      }
    }
  },
  mounted() {
    this.page() // 当页面加载完成后，发送异步请求，获取数据
  },
  methods: {
    // 查询分页数据
    page() {
      const requestData = {
        number: this.queryParams.number,
        name: this.queryParams.name,
        phoneNumber: this.queryParams.phoneNumber,
        current: this.current,
        pageSize: this.pageSize
      }

      page(requestData).then((res) => {
        this.totalCount = res.data.total
        this.tableData = res.data.records
      }).catch((error) => {
        // 处理错误情况
        console.error('Error fetching data:', error)
      })
    },

    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 查询方法
    onSubmit() {
      this.current = 1
      this.page()
    },

    clear() {
      this.queryParams = { number: '', name: '', phoneNumber: '' }
      this.page()
    },

    // 添加数据
    add() {
      let operator

      if (this.teacher.id) {
        // 修改
        operator = update(this.teacher)
      } else {
        operator = add(this.teacher)
      }

      operator.then((resp) => {
        if (resp.code == '1') {
          this.dialogVisible = false
          this.page()
          this.$message({ message: '恭喜你，保存成功', type: 'success' })
        } else {
          this.$message.error(resp.msg)
        }
      })
    },
    update(id) {
      // 1. 打开窗口
      this.dialogVisible = true
      // 2. 发送请求
      selectById(id).then((result) => {
        if (result.code == 1) {
          this.teacher = result.data
        } else {
          this.$message.error('获取用户信息失败')
        }
      })
    },
    // 分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val
      this.page()
    },

    handleCurrentChange(val) {
      // 重新设置当前页码
      this.current = val
      this.page()
    },

    // 删除员工信息
    deleteById(id) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 2. 发送AJAX请求
        deleteById(id).then((resp) => {
          if (resp.code == 1) {
            // 删除成功
            this.$message.success('恭喜你，删除成功')
            this.page()
          } else {
            this.$message.error(resp.msg)
          }
        })
      }).catch(() => {
        // 用户点击取消按钮
        this.$message.info('已取消删除')
      })
    },

    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
